﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
using System.Drawing;
using System.Windows.Forms;

using iPhoneUI.Shell;
using iPhoneUI.Widgets;

namespace iPhoneUI
{
    public class PageFactory
    {
        private Form m_owner;

        public PageFactory(Form owner)
        {
            Debug.Assert(owner != null); 

            m_owner = owner;
        }

        public Page CreatePage(PageConfig pageConfig, Rectangle pageBounds)
        {
            Debug.Assert(pageConfig != null);

            Page instance = pageConfig.CreateInstance();
            instance.Owner = m_owner;
            instance.Name = pageConfig.Name;
            instance.Bounds = pageBounds;
            instance.BackgroundAlpha = pageConfig.BackgroundAlpha;
            instance.BackgroundImage = pageConfig.CreateBackgroundImage();
            instance.Name = pageConfig.Name;
            instance.WidgetRefs = pageConfig.WidgetRefs;
            instance.SetProperties(pageConfig.Properties);

            // create widgets in the order of their snapstyle to get correct placement
            CreateWidgets(instance, pageConfig.Widgets.Where(w => w.SnapStyle == SnapStyle.Top), pageBounds);
            CreateWidgets(instance, pageConfig.Widgets.Where(w => w.SnapStyle == SnapStyle.Bottom), pageBounds);
            CreateWidgets(instance, pageConfig.Widgets.Where(w => w.SnapStyle == SnapStyle.Fill), pageBounds);
            CreateWidgets(instance, pageConfig.Widgets.Where(w => w.SnapStyle == SnapStyle.None), pageBounds);

            return instance;
        }

        private void CreateWidgets(Page instance, IEnumerable<WidgetConfig> configs, Rectangle bounds)
        {
            foreach (WidgetConfig config in configs)
            {
                Widget widget = WidgetFactory.CreateWidget(instance, config);
                WidgetFactory.PlaceWidget(bounds, instance.Widgets.Values, widget);

                instance.Widgets.Add(config.Name, widget);
            }
        }
    }
}
